package Lib3d.PresetModel3d;


import Lib3d.Vector3d;
import Lib3d.Animation.SimpleAnimationImpl;
import Lib3d.MyUtils.Debug;
import Lib3d.Physics.Mass;
import Lib3d.Physics.Spring;
import Lib3d.SceneGraph.Impl.ObjectNodeImpl;

import java.awt.Color;
import java.util.Vector;

import javax.media.opengl.GLAutoDrawable;

/**
 * A hair 3d model implementation.
 * 
 * @author Wassim Chegham
 * @version 0.1
 * @category Lib3d.PresetModel3d
 * 
 */
public class Hair extends ObjectNodeImpl {

    private final Vector<Mass> massList = new Vector<Mass>();
    private final Vector<Spring> springList = new Vector<Spring>();
    private final float springLenght = 5f;
    private final static int NB_MASS = 4;
    private final float dt = .5f * .5f;
    private final Color color;

    public Hair(final Vector3d initPosition, final float theta, final float phi,
            final Color color) {

        // first mass
        Mass currentMass = new Mass(initPosition);
        Mass nextMass;
        this.massList.add(currentMass);

        this.color = color;

        // other masses
        Vector3d nextPosition;
        int i = 0;
        float n = 0;
        float x, y, z;
        for (i = 1; i < Hair.NB_MASS; i++) {

            n = this.springLenght * i;
            x = (float) (n * Math.sin(theta) * Math.cos(phi)) + initPosition.get(0);
            y = (float) (n * Math.sin(theta) * Math.sin(phi)) + initPosition.get(1);
            z = (float) (n * Math.cos(theta)) + initPosition.get(2);
            nextPosition = new Vector3d(x, y, z);
            nextMass = new Mass(nextPosition);
            this.springList.add(new Spring(currentMass, nextMass));
            this.massList.add(nextMass);
            currentMass = nextMass;

        }

    }

    public Hair animate() {
        for (int i = 0; i < this.springList.size(); i++) {
            this.springList.get(i).applyForce(SimpleAnimationImpl.getAnimationFunction())
                    .animate(this.dt);
        }
        return this;
    }

    @Override
    public void draw(final GLAutoDrawable gLDrawable) {
        super.draw(gLDrawable);

        for (int i = 0; i < this.springList.size(); i++) {
            this.springList.get(i).setColor(this.color).draw(gLDrawable);
        }

        if (Debug.showMasses) {
            for (int i = 0; i < this.massList.size(); i++) {
                this.massList.get(i).draw(gLDrawable);
            }
        }

    }

    public Vector<Mass> getMassList() {
        return this.massList;
    }

    public Vector<Spring> getSpringList() {
        return this.springList;
    }

    @Override
    public String toString() {
        String s = "\nHair:\n";
        for (int i = 0; i < this.springList.size(); i++) {
            s += "Spring" + i + ": " + this.springList.get(i) + "\n";
        }
        return "\n" + s;
    }
}
